package com.itheima.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.domain.front.Member;
import com.itheima.utils.JedisUtils;
import com.itheima.web.controller.BaseServlet;
import com.itheima.web.controller.Code;
import com.itheima.web.controller.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: mm_exam_review
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-16 10:09
 **/
@WebServlet("/member/*")
public class MemberServlet extends BaseServlet {
    Logger logger = LoggerFactory.getLogger(MemberServlet.class);

    public Result logout(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        boolean flag = memberService.logout(id);
        if (flag) {

            return new Result(null, "删除成功");
        } else {

            return new Result(Code.LOGOUT_FAIL, null, "删除失败", false);
        }
    }

    public Result login(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Member m = JSON.parseObject(req.getInputStream(), Member.class);
        Member member = memberService.login(m.getEmail(), m.getPassword());
        if (member == null) {
            logger.info("没有登录成功");
            return new Result(Code.LOGIN_FAIL, null, " 用户名密码错误，请重试！", false);
        } else {
            Result result = new Result(member, "登录成功");
            logger.info("登录成功: " + result);

            return result;
        }
    }

    public Result checkLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String str = JSON.parseObject(req.getInputStream(), String.class);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String id = jsonObject.getObject("id", String.class);
        Jedis resource = JedisUtils.getResource();
        String nickName = resource.get(id);
        resource.close();
        if (StringUtils.isBlank(nickName)) {
            logger.info("没有登录");
            return new Result(Code.LOGIN_FAIL, null, "没有登录", false);
        } else {
            return new Result(nickName, "登录成功");

        }
    }
}
